<?php

namespace App\Models;

use App\Project\Transform;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class MedicalHpiSub extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    protected $table = 'st_medical_presentillness_sub';

    protected $fillable = [
        'record_id', 'started_at', 'inducement', 'clinic_site', 'symptoms',
        'before_treatment', 'after_treatment', 'diagnose', 'medication', 'cn_medication', 'type',
    ];

    protected $casts = [
        'medication'       => 'array',
        'cn_medication'    => 'array',
        'before_treatment' => 'array',
        'after_treatment'  => 'array',
    ];

    public function medicalRecord()
    {
        return $this->belongsTo(MedicalRecord::class, 'record_id');
    }

    /**
     * 获取现病史 type 值
     * @param $record
     * @return int
     */
    public function getTheType($record)
    {
        if ($record instanceof MedicalRecord) {
            $visit = $record->isFirstVisit();
        } else {
            $visit = MedicalRecord::where(['record_id' => $record])
                                  ->select('visit_type')->first()->isFirstVisit();
        }

        if ($visit)
            return 1;

        return 2;
    }

    /**
     * 现病史组批量存储
     * @param $input
     * @return int
     */
    public function hpiSubStoreForBatch($input)
    {
        $transform = new Transform();

        $hpiSub = [];

        foreach ($input as $item) {
            $hpiSub[] = $transform->setArray($item)->convertArrayToJson(
                ['medication', 'before_treatment', 'after_treatment']
            )->convertArrayToString(['diagnose'])->get();
        }

        return \DB::table('st_medical_presentillness_sub')->insertGetId($hpiSub);
    }

    public function setSymptomsAttribute($value)
    {
        if (is_array($value)) {
            $value = implode(',', $value);
        }

        $this->attributes['symptoms'] = $value;
    }

    public function setDiagnoseAttribute($value)
    {
        if (is_array($value)) {
            $value = implode(',', $value);
        }

        $this->attributes['diagnose'] = $value;
    }

    //  获取器
    public function getInducementAttribute($value)
    {
        if($value==0){
            $value=4;
        }
        return [
            'key'   => $value,
            'value' => app('field')->get('hpi.inducement')[$value]
        ];
    }

    public function getSymptomsAttribute($value)
    {
        return empty($value) ? $value : explode(',', $value);
    }

    public function getDiagnoseAttribute($value)
    {
        return DiseaseDictionary::select(['id', 'name', 'icd'])
                                ->whereIn('id', explode(',', $value))->get();
    }

    public function getStartedAtAttribute($value)
    {
        if (empty($value)) {
            return $value;
        }

        return Carbon::parse($value)->format('Y-m');
    }
}
